<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['psedu-exam:exam:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['psedu-exam:exam:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['psedu-exam:exam:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['psedu-exam:exam:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考试ID" align="center" prop="examId" width="80"/>
      <el-table-column label="考试名称" align="center" prop="examName"/>
      <el-table-column label="考试类型" align="center" prop="officialExam" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.exam_type" :value="scope.row.officialExam"/>
        </template>
      </el-table-column>
      <el-table-column label="允许开始考试" align="center" prop="allowStart" width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.allowStart"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :inactive-value="0"
            :active-value="1"
            active-text="允许"
            inactive-text="不允许"
            @change="changeExamAllowStart(scope.row, $event, scope.$index)"
            :disabled="scope.row.loading === true"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="总时间" align="center" prop="totalTime" width="100"  />
      <el-table-column label="分党校控制考试时间" align="center" prop="controlFlag" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.controlFlag === 1? "是" : "否"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间限制" align="center" prop="timeLimitStatus" width="100" >
        <template slot-scope="scope">
          <span>{{ scope.row.controlFlag === 1? "不限制" : "限制"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="最大重复考试次数" align="center" prop="maxRepeatCount" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['psedu-exam:exam:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['psedu-exam:exam:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考试发起对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left">
        <el-form-item label="学期ID" prop="semeId">
          <el-select
               v-model="form.semeId"
               :disabled="form.examId != null"
               placeholder="请输入学期"
               @change="changeExamName()"
               style="width: 100%"
          >
            <el-option
              v-for="item in semeList"
              :key="item.semeId"
              :label="item.semeName"
              :value="item.semeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试类型" prop="officialExam">
          <el-switch
            v-model="form.officialExam"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :inactive-value="0"
            :active-value="1"
            active-text="正式考试"
            inactive-text="模拟考试"
            @change="changeExamName()"
            :disabled="form.examId != null"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="form.examName" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="总时间" prop="totalTime">
          <el-input v-model="form.totalTime" placeholder="请输入总时间" />
        </el-form-item>
        <el-form-item label="分党校控制考试时间" prop="controlFlag" label-width="140px">
          <el-switch
            v-model="form.controlFlag"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :inactive-value="0"
            :active-value="1"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="最大重复考试次数" prop="maxRepeatCount" label-width="130px">
          <el-input v-model="form.maxRepeatCount" placeholder="请输入最大重复考试次数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExam, getExam, delExam, addExam, updateExam, updateExamAllowStart } from "@/api/psedu-exam/exam";
import { listSimpleSemester } from "@/api/psedu-base/semester";

export default {
  name: "Exam",
  dicts: ['exam_type', 'exam_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考试发起表格数据
      examList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        semeId: null,
        allowStart: null,
        controlFlag: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      semeList: [],
    };
  },
  created() {
    this.getList();

  },
  methods: {
    getSemeList() {
      return listSimpleSemester().then(resp => {
        this.semeList = resp.data;
        this.semeId = this.semeList[0].semeId;
        return Promise.resolve();
      })
    },
    /** 查询考试发起列表 */
    getList() {
      this.loading = true;
      listExam(this.queryParams).then(response => {
        this.examList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 根据semeID和officialExam确定考试名称 */
    changeExamName() {
      let semeName = '';
      this.semeList.forEach(seme => {
        if(seme.semeId === this.form.semeId) {
          semeName = seme.semeName;
        }
      })
      this.form.examName = semeName +(this.form.officialExam === 1 ? '正式考试' : '模拟考试');
    },
    // 更改允许开始考试状态
    changeExamAllowStart(row, $event, index, newValue) {
      console.log($event);
      row.loading = true;
      updateExamAllowStart(row.examId, row.allowStart).then(res => {
        console.log(res);
        row.loading = false;
        this.$set(this.examList, index, row);
      }).catch(err => {
        // 取反
        row.allowStart = row.allowStart === 0? 1: 0;
        row.loading = false;
        this.$set(this.examList, index, row);
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        examId: null,
        semeId: null,
        examName: '',
        paperRuleRepoId: null,
        allowStart: 0,
        controlFlag: 0,
        timeLimitStatus: 0,
        totalTime: 90,
        officialExam: 0,
        maxRepeatCount: 2,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.examId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考试发起";
      this.getSemeList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getSemeList();
      const examId = row.examId || this.ids
      getExam(examId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考试发起";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.examId != null) {
            updateExam(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExam(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const examIds = row.examId || this.ids;
      this.$modal.confirm('是否确认删除考试发起编号为"' + examIds + '"的数据项？').then(function() {
        return delExam(examIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('psedu-exam/exam/export', {
        ...this.queryParams
      }, `exam_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
